package warehouse;

import entity.CommodityLocalHome;
import excel.ExcelReportBuilder;
import helper.SimpleJSONArray;
import helper.SimpleJSONObject;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import report.ReportData;
import report.ReportDataFactory;

/**
 *
 * @author Oleh
 */
public class PopularityReport extends HttpServlet {

    public static final String warehouseParameter = "warehouse";
    public static final String startParameter = "start";
    public static final String quantityParameter = "quantity";
    public static final String actionParameter = "action";
    public static final String generateValue = "generate";
    public static final String exportValue = "export";
    
    public static final String warehouseProperty = "warehouse";
    public static final String commodityProperty = "commodity";
    public static final String quantityProperty = "quantity";
    public static final String fileProperty = "file";
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter(actionParameter);
        String warehouseString = request.getParameter(warehouseParameter);
        String startString = request.getParameter(startParameter);
        String quantityString = request.getParameter(quantityParameter);
        Integer warehouse = (warehouseString != null && !warehouseString.equals("")) ? Integer.valueOf(warehouseString) : null;
        Integer start = (startString != null && !startString.equals("")) ? Integer.valueOf(startString) : null;
        Integer quantity = (quantityString != null && !quantityString.equals("")) ? Integer.valueOf(quantityString) : null;
        
        System.out.println("action = " + action);
        System.out.println("warehouse = " + warehouse);
        System.out.println("start = " + start);
        System.out.println("quantity = " + quantity);
        
        try {
            Context context = new InitialContext();
            CommodityLocalHome commodityHome = (CommodityLocalHome) context.lookup("java:comp/env/Commodity");
            ArrayList report = commodityHome.getPopularityReport(warehouse, start, quantity);
            if (generateValue.equals(action)) {
                SimpleJSONArray array = new SimpleJSONArray();
                for (int i = 0; i < report.size(); i++) {
                    SimpleJSONObject record = new SimpleJSONObject();
                    transfer.PopularityReport current = (transfer.PopularityReport) report.get(i);
                    record.addProperty(warehouseProperty, current.warehouse);
                    record.addProperty(commodityProperty, current.commodity);
                    record.addProperty(quantityProperty, current.quantity.toString());
                    array.addElement(record);
                }
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print(array);
                out.flush();
                out.close();
            } 
            if (exportValue.equals(action)) {
                ReportData reportData = ReportDataFactory.getReportData(report);
                if (!ExcelReportBuilder.configLoaded) {
                    Properties props = ExcelReportBuilder.loadProperties();
                    String reportFolder = getServletContext().getRealPath("")
                                    + File.separator + props.getProperty("SAVE_PATH");
                    props.setProperty("SAVE_PATH", reportFolder);
                    ExcelReportBuilder.saveProperties(props);
                }                       
                String file = ExcelReportBuilder.buildReport(reportData);
                System.out.println("file = " + file);
                SimpleJSONObject json = new SimpleJSONObject();
                String[] names = file.split("\\\\");
                file = names[names.length - 2] + "/" + names[names.length - 1];
                json.addProperty(fileProperty, file);
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print(json);
                out.flush();
                out.close();
            }
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
